#include "tour.h"

char *lookup_hostbyip(char *cIP)
{
        struct hostent  *he;
        struct in_addr  addr;
        char            *hostname;

        memset(&addr, 0, sizeof(addr));
        inet_pton(AF_INET, cIP, &addr);

        he = gethostbyaddr(&addr, sizeof(addr), AF_INET);
        hostname = (char *) malloc(HOSTNAME_LEN);
        assert(hostname);

        if(he == NULL)
        {
                return "";
        }
        strcpy(hostname, he->h_name);

        return hostname;
}

int lookup_hostbyname(char *hostname, char *cIP)
{
        struct hostent *he;
        struct in_addr addr;

        memset(&addr, 0, sizeof(addr));
        he = gethostbyname(hostname);
        if(he == NULL)
        {
                return -1;
        }
        memcpy(&addr, he->h_addr_list[0], he->h_length);

        Inet_ntop(AF_INET, &addr, cIP, INET_ADDRSTRLEN);

        return 0;
}

char *getlohostname()
{
        struct hwa_info *hwa;
        struct sockaddr_in *sa;
        char *lohostname = "";

        for(hwa = Get_hw_addrs(); hwa != NULL; hwa = hwa->hwa_next)
        {
                sa = (struct sockaddr_in *) hwa->ip_addr;
char tmp_ip[INET_ADDRSTRLEN];
                Inet_ntop(AF_INET, &sa->sin_addr, tmp_ip, sizeof(tmp_ip));
                //check for lo and eth0
                if(strncmp(hwa->if_name, "eth0", 4) == 0)
                {
                        if (strcmp(hwa->if_name, "eth0") == 0) {
                                lohostname = lookup_hostbyip(tmp_ip);
                                break;
                        }
                }
        }
        return lohostname;

}

